<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { baseURL } from '@/utils/request'
// 注意：
//  ✅ @hyoga/uni-socket.io 才是兼容多端的 socket 库
//  ❌ socket.io-client 只能兼容 H5 端
import io from '@hyoga/uni-socket.io'
import RoomStatus from './components/room-status.vue'
import { getPatientConsultOrderDetailAPI } from '@/apis/consult'
import { ref } from 'vue'
import type { GetPatientConsultOrderDetailData } from '@/types/consult'
import type { ChatMsgListData, MsgItem, Prescription } from '@/types/room'
import PatientInfo from './components/patient-info.vue'
import NotifyInfo from './components/notify-info.vue'
import MessageInfo from './components/message-info.vue'
import PrescriptionInfo from './components/prescription-info.vue'

// 页面参数
const props = defineProps<{
  payResult: 'true' | 'false'
  orderId: string
  type: string
}>()

// 创建 socket 连接
const store = useUserStore()
const socket = io(baseURL, {
  // 传递 token，用于身份认证（后端要求）
  auth: { token: `Bearer ${store.token}` },
  // 传递订单 id，用于查询订单信息（后端要求）
  query: { orderId: props.orderId },
  // 为了更好的兼容性：支持 websocket 和 轮询 两种传输方式
  transports: ['websocket', 'polling'],
  // 超时时间
  timeout: 5000,
})

const orderDetail = ref<GetPatientConsultOrderDetailData>()
const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI(props.orderId)
  orderDetail.value = res.data
}
getOrderDetail()

// 监听订单状态变化，statusChange 为后端定义的事件名称
socket.on('statusChange', () => {
  // 重新获取订单详情，包含订单状态，倒计时秒数
  getOrderDetail()
})

// 处方信息
// 消息列表
const msgList = ref<MsgItem[]>([])
// 历史消息，事件名称为 chatMsgList
socket.on('chatMsgList', (res: ChatMsgListData) => {
  // 业务状态码
  if (res.code !== 10000) return
  // 循环消息组（消息组按时间节点划分，一个消息组包含多个消息）
  res.data?.forEach((item) => {
    // 如果有消息列表，则追加到数组中
    if (item.items) {
      msgList.value.push(...item.items)
    }
  })
  console.log(msgList.value)
})

// 接收消息
socket.on('receiveChatMsg', (res: MsgItem) => {
  // 追加消息
  msgList.value.push(res)
  // 消息已读
  socket.emit('updateMsgStatus', res.id)
})

socket.on('connect', () => {
  console.log('连接成功')
})

socket.on('disconnect', () => {
  console.log('连接失败')
})
</script>

<template>
  <view class="room-page">
    <!-- 咨询室状态组件 -->
    <RoomStatus
      v-if="orderDetail"
      :status="orderDetail?.status"
      :statusValue="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown"
    />
    <!-- 消息列表 -->
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="item in msgList" :key="item.id">
          {{ item.msgType }}
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <NotifyInfo v-else-if="item.msgType && item.msgType >= 31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <!-- 处方信息 -->
          <PrescriptionInfo
            v-else-if="item.msgType === 22"
            :type="item.msg?.prescription"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          disabled
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
